package com.gzz.orchid.main.facade.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author higmd
 */
@Slf4j
@RestController
@RequestMapping("/async")
public class AsyncController {
    @RequestMapping("/async-task")
    @ResponseBody
    public WebAsyncTask<String> asyncTask() {
        // 1000 为超时设置
        WebAsyncTask<String> webAsyncTask = new WebAsyncTask<String>(1000, new Callable<String>() {
            @Override
            public String call() throws Exception {
                //业务逻辑处理
                Thread.sleep(5000);
                return "username:wangbinghua";
            }
        });
        webAsyncTask.onCompletion(new Runnable() {
            @Override
            public void run() {
                System.out.println("调用完成");
            }
        });
        webAsyncTask.onTimeout(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("业务处理超时");
                return "<h1>Time Out</h1>";
            }
        });
        return webAsyncTask;
    }

    @GetMapping("/deferredResultUser")
    public DeferredResult<String> deferredResultListUser() {
        DeferredResult<String> deferredResult
                = new DeferredResult<>(20000L, "失败");
        deferredResult.onTimeout(() -> {
            log.info("调用超时");
            //调用超时这个 超时结果会覆盖 构造时的超时结果
            deferredResult.setResult("调用超时");
        });
        deferredResult.onCompletion(() -> {
            log.info("调用完成");
        });
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
                deferredResult.setResult("OK");
            } catch (InterruptedException e) {
                //e.printStackTrace();
                log.info("调用失败" + e.getMessage());
            }
        }).start();
        return deferredResult;

    }

}
